package com.lhj.xxsc.order.web;

import com.xxsc.common.exception.NoStockExceptoin;
import com.lhj.xxsc.order.service.OrderService;
import com.lhj.xxsc.order.vo.OrderConfirmVo;
import com.lhj.xxsc.order.vo.OrderSubmitVo;
import com.lhj.xxsc.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

/**
 * @author 罗惠江
 * @version 1.0
 * @email 1511619294@qq.com
 * @date 2021/1/4 13:55
 */
@Controller
public class OrderWebController {
	@Autowired
	OrderService orderService;

	@GetMapping("/{page}.html")
	public String listPage(@PathVariable("page") String page) {
		System.out.println(page);
		return page;
	}

	@GetMapping("/toTrade")
	public String toTrade(Model model) throws ExecutionException, InterruptedException {
		OrderConfirmVo orderConfirmVo = orderService.confirmOrder();
		// 展示订单
		model.addAttribute("orderConfirmData", orderConfirmVo);
		return "confirm";
	}


	/**
	 * 提交下单功能
	 *
	 * @param vo
	 * @return
	 */
	@PostMapping("/submitOrder")
	public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes) {
		// 创建订单，验令牌，验价格，锁库存
		// 成功，支付页面
		// 失败，确定页
		try {
			SubmitOrderResponseVo orderResponseVo = orderService.submitOrder(vo);
			if (orderResponseVo.getCode() == 0) {
				// 成功
				model.addAttribute("orderResponseVo", orderResponseVo);
				return "pay";
			} else {
				String msg = "下单失败!";
				switch (orderResponseVo.getCode()) {
					case 1:
						msg += "订单信息过期，请刷新后重新提交。";
						break;
					case 2:
						msg += "订单价格发生变化，请确认后再次提交。";
						break;
					case 3:
						msg += "库存不足，请确认后再次提交。";
				}
				redirectAttributes.addFlashAttribute("msg", msg);
				return "redirect:http://order.xxsc.com/toTrade";
			}
		} catch (Exception e) {
			if (e instanceof NoStockExceptoin) {
				String message = ((NoStockExceptoin) e).getMessage();
				redirectAttributes.addFlashAttribute("msg", message);
			}
			return "redirect:http://order.xxsc.com/toTrade";
		}

	}
}
